
Ext.onReady(function() {
	Ext.define('HouseKeeperModel', {
        extend: 'Ext.data.Model',
        fields: [
            { name: 'QUERYID', type: 'string'},
            { name: 'ITEMS', type: 'string'},
            { name: 'ACTIONDATE', type: 'date'}
        ]
    });
	
	var store = Ext.create('Ext.data.Store',{
		pageSize : 20,
		model : 'HouseKeeperModel'
	});
	
	var rowEditing = Ext.create('Ext.grid.plugin.RowEditing', {
        clicksToMoveEditor: 1,
        autoCancel: true,
        listeners:{
        	edit:{
        		fn:spendItemEdit
        	}
        }
    });
	
	var oneDate = new Date();
	oneDate.setDate(1);
	
	var startDate = Ext.create('Ext.form.field.Date', {
		xtype: 'datefield',
        fieldLabel: str_housekeeper2_spendtime,
        editable: false,
        value: oneDate
	});
	
	var to = Ext.create('Ext.form.Label',{
		text:'~'
	});
	
	var endDate = Ext.create('Ext.form.field.Date',{
		xtype: 'datefield',
        editable: false,
        value: new Date()
	});
	
	var grid = Ext.create('Ext.grid.Panel', {
		region: 'center',
		split: true,
		store : store,
		loadMask : true,
		multiSelect : true,
		columns: [
          {
              xtype: 'rownumberer',
              width: 30
          },
          {
              xtype: 'gridcolumn',
              dataIndex: 'ITEMS',
              flex: 1,
              hideable: false,
              text: str_housekeeper2_project,
              editor : {}
          },
          {
              xtype: 'datecolumn',
              width: 140,
              dataIndex: 'ACTIONDATE',
              hideable: false,
              text: str_housekeeper2_date,
              format : 'Y-m-d',
              editor : {
            	  xtype: 'datefield',
            	  format:'Y-m-d'
              }
          },
          {
              xtype: 'actioncolumn',
              draggable: false,
              sortable: false,
              hideable: false,
              width: 60,
              items: [
                  {
                	  icon:getPath('/common/images/delete.png'),
                	  handler : function(grid, rowIndex, colIndex){
                		  var id = store.getAt(rowIndex).get('QUERYID');
                		  if (id != null && id != "") {
                			  Ext.MessageBox.confirm(str_common_confirm,str_common_confirmdel, function(button, text) {
                				  if(button == "yes") {
                					  Ext.Ajax.request({
            							  url : getPath('/ab/po/houseKeeper2.do'),
            							  params : {
            								  md : 'deleteKeeper',
            								  ID : [id]
            							  },
            					          success : function(response) {  
            					                var ret = Ext.JSON.decode(response.responseText);
            					                if(ret.success){
            					                	rowEditing.cancelEdit();
            	                					var sm = grid.getSelectionModel();
            	                					sm.select(rowIndex);
            	                					store.remove(sm.getSelection());
            					                }
            					                else {
            					                    Ext.MessageBox.alert(str_common_error,ret.msg);
            					                }
            					          }
            						  });
                				  }
                			  });
                		  }
                		  else {
                			  rowEditing.cancelEdit();
        					  var sm = grid.getSelectionModel();
        					  sm.select(rowIndex);
        					  store.remove(sm.getSelection());
                		  }
                	  }
                  }
              ]
          }
        ],
        dockedItems: [
          {
              xtype: 'toolbar',
              dock: 'top',
              items: [
                  {
                      xtype: 'button',
                      iconCls:'icon-add',
                      text: str_common_add,
                      listeners: {
                          click: {
                        	  fn:addRow
                          }
                      }
                  },
                  '-',
                  startDate,
                  to,
                  endDate,
                  '-',
                  {
                      xtype: 'button',
                      text: str_common_query,
                      listeners: {
                          click: {
                              fn: query
                          }
                      }
                  }
              ]
          },
          {
              xtype: 'pagingtoolbar',
              displayInfo: true,
              store: store,
              dock: 'bottom'
          }
        ],
        plugins: [rowEditing],
        maxHeight:600
	});
	
	function addRow() {
		rowEditing.cancelEdit();
		var r = Ext.create('HouseKeeperModel', {
			ID: '',
			ITEMS : '',
			ACTIONDATE: Ext.Date.format(new Date(), 'Y-m-d')
        });
		store.insert(0, r);
        rowEditing.startEdit(0, 0);
	}
	
	function query(){
		store.setProxy({
			type : 'ajax',
			url : getPath("/ab/po/houseKeeper2.do"),
			extraParams : {
            	"md":"readKeeper",
            	"STARTDATE":startDate.getRawValue(),
            	"ENDDATE":endDate.getRawValue()
            },
			reader : {
				type : 'json',
				root : 'housekeeper',
				totalProperty : 'totalCount'
			}
		});
		store.loadPage(1);
	}
	
	function spendItemEdit(editor, e) {
		//alert("DDD");
        Ext.Ajax.request({
            url : getPath("/ab/po/houseKeeper2.do"),
            actionMethods: 'POST',
            params : {
            	"md":"updateOrCreate",
                "QUERYID" : e.record.data['QUERYID'],
                "ITEMS" : e.record.data['ITEMS'],
                "ACTIONDATE" : e.record.data['ACTIONDATE']
            },
            success : function(response) {  
            	var ret = Ext.JSON.decode(response.responseText);
            	if(ret.success){
                    e.record.data['QUERYID'] = ret.msg;
                    e.record.commit();
            	}
            	else {
            		Ext.MessageBox.alert(str_common_error,ret.msg);
            	}
            }
        });
	}
	
	var addSpendWin = Ext.create('Ext.Window', {
		maximizable: true,
		title: str_housekeeper2_costrecord,
        height: 550,
        width: 600,
        layout: 'fit',
        items: [grid],
        closeAction: 'hide',
        x: 10,
        y: 35,
        listeners:{
        	hide:function(){
        		if(addSpendBtn.pressed){
        			addSpendBtn.toggle();
        		}
        	}
        }
    }).show();
	
	Ext.define('HouseKeeperSpendTypeModel', {
        extend: 'Ext.data.Model',
        fields: [
            { name: 'QUERYCODE', type: 'string'},
            { name: 'CODE', type: 'string'},
            { name: 'CODENAME', type: 'string'}
        ]
    });
	
	var spendTypeStore = Ext.create('Ext.data.Store',{
		model : 'HouseKeeperSpendTypeModel'
	});
	
	var spendTypeRowEditing = Ext.create('Ext.grid.plugin.RowEditing', {
        clicksToMoveEditor: 1,
        autoCancel: true,
        listeners:{
        	edit:{
        		fn:onSpendTypeEdit
        	}
        }
    });
	
	var spendTypeGrid = Ext.create('Ext.grid.Panel', {
		region: 'center',
		split: true,
		store : spendTypeStore,
		loadMask : true,
		multiSelect : true,
		plugins: [spendTypeRowEditing],
		columns: [
          {
              xtype: 'rownumberer',
              width: 30
          },
          {
              xtype: 'gridcolumn',
              dataIndex: 'CODE',
              width: 80,
              hideable: false,
              text: str_housekeeper2_code,
              editor : {
              }
          },
          {
              xtype: 'gridcolumn',
              flex: 1,
              dataIndex: 'CODENAME',
              hideable: false,
              text: str_housekeeper2_name,
              editor : {
              }
          },
          {
              xtype: 'actioncolumn',
              draggable: false,
              sortable: false,
              hideable: false,
              width: 40,
              items: [
                  {
                	  icon:getPath('/common/images/delete.png'),
                	  handler : function(grid, rowIndex, colIndex){
                		  var code = spendTypeStore.getAt(rowIndex).get('QUERYCODE');
                		  if (code != null && code != "") {
                			  if("default"==code){
                				  Ext.MessageBox.alert(str_common_error,str_housekeeper2_cantdelete);
                				  return false;
                			  }
                			  Ext.MessageBox.confirm(str_common_confirm,str_common_confirmdel, function(button, text) {
                				  if(button == "yes") {
                					  Ext.Ajax.request({
            							  url : getPath('/ab/po/houseKeeper2.do'),
            							  params : {
            								  md : 'deleteSpendType',
            								  CODE : [code]
            							  }
            						  });
                					  spendTypeRowEditing.cancelEdit();
                					  var sm = grid.getSelectionModel();
                					  sm.select(rowIndex);
                					  spendTypeStore.remove(sm.getSelection());
                				  }
                			  });
                		  }
                		  else {
                			  spendTypeRowEditing.cancelEdit();
        					  var sm = grid.getSelectionModel();
        					  sm.select(rowIndex);
        					  spendTypeStore.remove(sm.getSelection());
                		  }
                	  }
                  }
              ]
          }
        ],
        dockedItems: [
          {
              xtype: 'toolbar',
              dock: 'top',
              items: [
                  {
                      xtype: 'button',
                      iconCls:'icon-add',
                      text: str_common_add,
                      listeners: {
                          click: {
                        	  fn:addSpendTypeRow
                          }
                      }
                  },
                  {
                      xtype: 'tbseparator'
                  },
                  {
                      xtype: 'button',
                      text: str_common_query,
                      listeners: {
                          click: {
                              fn: querySpendType
                          }
                      }
                  }
              ]
          }
        ]
	});
	
	function onSpendTypeEdit(editor, e){
		Ext.Ajax.request({
            url : getPath("/ab/po/houseKeeper2.do"),
            actionMethods: 'POST',
            params : {
            	"md":"updateOrCreateSpendType",
                "QUERYCODE" : e.record.data['QUERYCODE'],
                "CODE" : e.record.data['CODE'],
                "CODENAME" : e.record.data['CODENAME']
            },
            success : function(response) {  
            	var ret = Ext.JSON.decode(response.responseText);
            	if(ret.success){
                    e.record.data['QUERYCODE'] = ret.msg;
                    e.record.commit();
            	}
            	else {
            		Ext.MessageBox.alert(str_common_error,ret.msg);
            	}
            }
        });
	}
	
	function querySpendType(){
		spendTypeStore.setProxy({
			type : 'ajax',
			url : getPath("/ab/po/houseKeeper2.do"),
			extraParams : {
            	"md":"readSpendType"
            },
			reader : {
				type : 'json',
				root : 'spendtype',
				totalProperty : 'totalCount'
			}
		});
		spendTypeStore.loadPage(1);
	}

	function addSpendTypeRow(){
		spendTypeRowEditing.cancelEdit();
		var r = Ext.create('HouseKeeperSpendTypeModel', {
			CODE: '',
			CODENAME : ''
        });
		spendTypeStore.insert(0, r);
		spendTypeRowEditing.startEdit(0, 0);
	}
	
	var addSpendTypeWin = Ext.create('Ext.Window', {
		maximizable: true,
		title: str_housekeeper2_costtype,
        height: 500,
        width: 300,
        layout: 'fit',
        closeAction: 'hide',
        items: [spendTypeGrid],
        x: 650,
        y: 40,
        listeners:{
        	hide:function(){
        		if(addSpendTypeBtn.pressed){
        			addSpendTypeBtn.toggle();
        		}
        	},
        	beforeshow: function(){
        		if(spendTypeStore.getTotalCount()==0) {
        			querySpendType();
        		}
        	}
        }
    });
	
	var addSpendBtn = new Ext.create('Ext.button.Button',{
		text: str_housekeeper2_costrecord,
		pressed: true,
        enableToggle: true,
		listeners:{
			click: function(){
				if(addSpendWin.isHidden()){
					addSpendWin.show();
				}
				else {
					addSpendWin.hide();
				}
			}
		}
	});
	
	var addSpendTypeBtn = new Ext.create('Ext.button.Button',{
		text: str_housekeeper2_costtype,
		pressed: false,
        enableToggle: true,
        listeners:{
			click: function(){
				if(addSpendTypeWin.isHidden()){
					addSpendTypeWin.show();
				}
				else {
					addSpendTypeWin.hide();
				}
			}
		}
	});
	
	var panel = Ext.create('Ext.panel.Panel',{
		region: 'center',
		dockedItems: [
		    {
				xtype: 'toolbar',
				dock: 'top',
				items:[
                    addSpendBtn,'-',addSpendTypeBtn
				]
		    }
		]
	});
	
	var view = Ext.create('Ext.container.Viewport', {
		layout : 'border',
		renderTo : Ext.getBody(),
		items : [panel]
	});
});